<template>
  <div class="main">
    <p class="main_text">商家须知</p>
    <!-- #################################### 表单 #################################### -->
    <div class="cyr-flex">
      <el-button type="primary" @click="addFormShowFlag" v-if="showFlag && roleList.write" style="width: fit-content">添加须知</el-button>
      <el-table @selection-change="handleSelectionChange" :data="tableData"class="mt20"
        :header-cell-style="{ background: '#f0f6fe' }"  :show-overflow-tooltip="true" v-adaptive border>
        <el-table-column type="selection" width="50" />
        <el-table-column label="编号" prop="id" />
        <!-- <el-table-column label="标题" prop="title" /> -->
        <el-table-column label="标题" prop="title">
          <template #default="props">
            <el-text tag="span" style="cursor: pointer" @click="checkBtn(props.row.id)">{{ props.row.title }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="版本号" prop="versionNumber" />
        <el-table-column label="生效时间" prop="effectiveDateD" />
        <el-table-column label="更新时间" prop="updatedAtD" />
        <el-table-column label="适用范围" prop="scopeOfApplication" />
        <!-- <el-table-column label="内容" prop="content" /> -->
        <el-table-column label="操作" fixed="right" width="100" :show-overflow-tooltip="false">
          <template #default="props">
            <el-button size="small" link type="primary" @click="checkBtn(props.row.id)"
              v-if="roleList.read">查看</el-button>
            <el-button size="small" link type="primary" @click="editBtn(props.row)"
              v-if="showFlag && roleList.write">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- #################################### 分页 #################################### -->
      <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="Number(total)"
        @change="handleCurrentChange" />
    </div>

    <!-- <textarea id="mytextarea" v-model="addFormData.content"></textarea> -->
  </div>
  <!--------------------------------- 添加须知 --------------------------------->
  <div class="maskk" v-show="centerDialogVisible" @click="closecenterDialogVisible">
    <div class="mask" @click="handleChildClick($event)">
      <div class="mask_nav">
        <div class="df aic">
          <el-icon style="color: #fff" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p style="color: #fff" v-if="titleShowFlag == false">添加须知</p>
          <p style="color: #fff" v-else>编辑须知</p>
        </div>
        <el-icon style="color: #fff" size="20" @click="closeDialogBtn">
          <Close />
        </el-icon>
      </div>
      <el-form :model="addFormData" ref="addFormDataRef" :rules="addFormDataRules" label-width="7.5rem"
        style="padding: 53px 0 0 0">
        <el-form-item label="须知标题：" style="width: 60%" prop="title">
          <el-input v-model="addFormData.title" />
        </el-form-item>
        <el-form-item label="版本号：" style="width: 60%" prop="versionNumber">
          <el-input v-model="addFormData.versionNumber" />
        </el-form-item>
        <el-form-item label="生效时间：" prop="effectiveDate">
          <el-date-picker v-model="addFormData.effectiveDate" type="datetime" :disabled-date="disableDate"
            :default-time="defaultTime(0, 0, 0)" value-format="YYYY-MM-DDTHH:mm:ss" />
        </el-form-item>
        <el-form-item label="适用范围：" style="width: 60%" prop="scopeOfApplication">
          <el-input v-model="addFormData.scopeOfApplication" />
        </el-form-item>
        <el-form-item label="须知内容：" style="width: 100%">
          <textarea id="mytextarea" :model="addFormData.content"></textarea>
        </el-form-item>
      </el-form>
      <div class="footer">
        <div>
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addSaveBtn(addFormDataRef)"> 确定 </el-button>
        </div>
      </div>
    </div>
  </div>
  <!--------------------------------- 查看须知 --------------------------------->
  <el-dialog v-model="checkFormDatacenterDialogVisible" title="查看须知" width="40%" align-center>
    <template #header>
      <div class="df aic">
        <el-icon style="color: #fff" size="20">
          <Edit />
        </el-icon>&nbsp;
        <p style="color: #fff">查看须知</p>
      </div>
    </template>
    <div style="font-size: 12px; max-height: 600px; overflow: scroll">
      <p style="text-align: center; font-weight: bold">{{ checkFormData.title }}</p>
      <p style="text-align: right"><span style="font-weight: bold">版本号：</span>{{ checkFormData.versionNumber }}</p>
      <p style="text-align: right">
        <span style="font-weight: bold">生效时间：</span>{{ checkFormData.effectiveDate }}
      </p>
      <p class="mb10" v-html="checkFormData.content"></p>
      <p style="text-align: right; font-weight: bold">四川劣车宝科技有限公司</p>
      <p style="text-align: right"><span style="font-weight: bold">更新时间：</span>{{ checkFormData.updatedAt }}</p>
      <hr class="mt20" />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="checkFormDatacenterDialogVisible = false"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Edit, Close } from '@element-plus/icons-vue';
import { formatTimeAll } from '../../../filters/index';
import {
  RequestNotificationSave,
  RequestNotificationGetlistlimit,
  RequestNotificationId,
  RequestArticleUpload,
  RequestArticlePhotoUpload,
} from '@/api/path/index.js';
import useAuthorize from '@/hooks/authorize';
let roleList = useAuthorize();
const handleChildClick = (event: any) => {
  event.stopPropagation();
};
const centerDialogVisible = ref<any>(false);
const EditCenterDialogVisible = ref<any>(false);
const EditCenterDialogVisibleFlag = ref<any>(false);
const checkFormDatacenterDialogVisible = ref<any>(false);
const tableData = ref<any>([]);
const showFlag = ref<any>(JSON.parse(localStorage.getItem('roleInfo')!).company == 0 ? true : false);
const searchData = ref<any>({
  title: '',
  scopeOfApplication: '',
});
const searchBtn = () => {
  currentPage.value = 1;
  getData();
};
const titleShowFlag = ref<any>(false);
const resetBtn = () => {
  currentPage.value = 1;
  searchData.value.title = null;
  searchData.value.scopeOfApplication = null;
  getData();
};
/* ************************ 分页获取数据 ************************ */
const multipleSelection = ref<any>([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};
const total = ref<any>(0);
const currentPage = ref(1);
const pageSize = ref(10);
const getData = () => {
  RequestNotificationGetlistlimit({
    page: currentPage.value,
    title: searchData.value.title,
    scopeOfApplication: searchData.value.scopeOfApplication,
    rows: pageSize.value,
  }).then((res: any) => {
    console.log(res);
    res.resultObj.data.forEach((item: any) => {
      item.effectiveDateD = formatTimeAll(item.effectiveDate);
      item.updatedAtD = formatTimeAll(item.updatedAt);
    });
    tableData.value = res.resultObj.data;
    total.value = res.resultObj.total;
    // centerDialogVisible.value = false
  });
};
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`)
  getData();
};
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`)
  getData();
};
/*------------------------------ 添加须知 ------------------------------*/
const addFormShowFlag = () => {
  tinymce.get('mytextarea').setContent('');
  addFormData.value.title = '';
  addFormData.value.versionNumber = '';
  addFormData.value.effectiveDate = '';
  addFormData.value.updatedAt = '';
  addFormData.value.scopeOfApplication = '';
  titleShowFlag.value = false;
  centerDialogVisible.value = true;
};
const addFormDataRef = ref<any>();
const addFormDataRules = ref<any>({
  title: [
    { required: true, message: '请填写须知标题', trigger: 'blur' },
    { min: 1, max: 40, message: '长度必须小于40个字符', trigger: 'blur' },
  ],
  versionNumber: [
    { required: true, message: '请填写版本号', trigger: 'blur' },
    { min: 1, max: 40, message: '长度必须小于40个字符', trigger: 'blur' },
  ],
  effectiveDate: [{ required: true, message: '请选择生效时间', trigger: 'blur' }],
  scopeOfApplication: [
    { required: true, message: '请填写适用范围', trigger: 'blur' },
    { min: 1, max: 40, message: '长度必须小于40个字符', trigger: 'blur' },
  ],
  content: [{ required: true, message: '请填写须知内容', trigger: 'change' }],
});
const addFormData = ref<any>({
  title: '',
  versionNumber: '',
  effectiveDate: '',
  updatedAt: '',
  scopeOfApplication: '',
  content: '',
});

// 挂载
onMounted(() => {
  // 先移除以前的
  tinymce.remove('#mytextarea');

  // tinymce.init({
  //   selector: "#mytextarea",
  //   language: "zh_CN",
  //   branding: false,
  //   height: 520,//富文本高度
  // });
  tinymce.init({
    selector: '#mytextarea',
    branding: false,
    width: 1400,
    height: 300,
    paste_data_images: true,
    // 图片上传
    images_upload_handler: function (blobInfo, success, failure) {
      file.value = blobInfo.blob();
      console.log('123', file.value);
      new Promise((resolve, reject) => {
        RequestArticlePhotoUpload({ img: file.value })
          .then((res: any) => {
            resolve(res);
            success(res.resultObj);
          })
          .catch((err: any) => {
            reject(err);
            failure('请求失败');
          });
      });
    },
    autosave_interval: '5s', //自动保存
    // selector: 'textarea',
    plugins: [
      'advlist lists link image charmap print preview anchor directionality textcolor',
      'searchreplace visualblocks code fullscreen',
      'insertdatetime media table paste help wordcount',
    ],
    fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',
    font_formats:
      "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
    menubar: 'file edit view insert format tools table help ',
    toolbar:
      'undo redo | formatselect | alignleft aligncenter alignright alignjustify | indent outdent | styleselect | forecolor backcolor bold italic | fontsizeselect | fontselect | image media table | removeformat code link insertdatetime charmap print searchreplace visualblocks fullscreen wordcount paste',
    media_live_embeds: true,
    media_dimensions: false,
    style_formats: [
      { title: '首行缩进', block: 'p', styles: { 'text-indent': '2em' } },
      { title: '1.5倍行间距', selector: 'p', styles: { 'line-height': '1.5' } },
      { title: '2倍行间距', selector: 'p', styles: { 'line-height': '2' } },
      { title: '2.5倍行间距', selector: 'p', styles: { 'line-height': '2.5' } },
      { title: '字体加粗', selector: 'span,strong', styles: { 'font-weight': '600' } },
    ],
    forced_root_block: false, // 禁用默认的换行标签
    force_br_newlines: true, // 强制将换行符转换为 <br> 标签
    force_p_newlines: false, // 禁止将连续换行符转换为 <p> 标签
  });
  // optionsList()
  // console.log('挂载', ruleForm.value)
});
getData();

// 随机切换富文本框id
const tinymceId = computed(() => {
  return `tiny-${Date.now()}`;
});
const disableDate = (time: any) => {
  return time.getTime() < Date.now() - 8.64e7;
};
const defaultTime = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};

const addSaveBtn = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate((valid: any) => {
    if (valid) {
      const editor = tinymce.get('mytextarea');
      if (editor) {
        let content = editor.getContent();
        let plainText = content.replace(/<p>/gi, '').replace(/<\/p>/gi, '');
        addFormData.value.content = plainText;
        // addFormData.value.content = editor.getContent().replace(/<p>/gi, '').replace(/<\/p>/gi, '')
        RequestNotificationSave(addFormData.value).then((res: any) => {
          if (res.success == true) {
            getData();
            ElMessage.success(res.msg);
            centerDialogVisible.value = false;
          }
        });
      }
    }
  });
};
const closecenterDialogVisible = () => {
  centerDialogVisible.value = false;
  addFormData.value.title = '';
  addFormData.value.versionNumber = '';
  addFormData.value.effectiveDate = '';
  addFormData.value.scopeOfApplication = '';
  addFormData.value.content = '';
  getData();
};
/*------------------------------ 编辑须知 ------------------------------*/
const editFormData = ref<any>({});
const file = ref();
const tinymceTxt = ref();

// 随机切换富文本框id
const editBtn = (e: any) => {
  titleShowFlag.value = true;
  centerDialogVisible.value = true;
  addFormData.value = e;
  tinymce.get('mytextarea').setContent(e.content);
};
/*------------------------------ 查看 ------------------------------*/
const checkFormData = ref<any>({});
const checkBtn = (e: any) => {
  RequestNotificationId(e).then((res: any) => {
    console.log(res.resultObj);
    if (res.success == true) {
      checkFormDatacenterDialogVisible.value = true;
      res.resultObj.effectiveDate = formatTimeAll(res.resultObj.effectiveDate);
      res.resultObj.updatedAt = formatTimeAll(res.resultObj.updatedAt);
      checkFormData.value = res.resultObj;
    }
  });
};
const closeDialogBtn = () => {
  centerDialogVisible.value = false;
};
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .top {
    width: 100%;
    background-color: #fff;
  }

  .content {
    width: 100%;
    background-color: #fff;
  }
}

/* 弹出框样式 */
::v-deep .el-overlay {
  .el-dialog__header {
    background-color: #116cf8;
    margin-right: 0;
  }

  .el-dialog__title {
    color: #fff;
  }

  .el-icon svg {
    color: #fff;
  }
}

.maskk {
  width: 100vw;
  height: 100vh;
  background-color: rgba($color: #000000, $alpha: 0.5);
  position: fixed;
  margin: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 1800;

  .mask {
    width: 60%;
    background-color: #fff;
    height: 84%;
    padding: 20px;
    overflow: scroll;
    position: fixed;
    margin: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    z-index: 2000;
    // display: none !important;

    // border-radius: 2%;
    .mask_nav {
      width: 100%;
      height: 53px;
      padding: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #2e5882;
      position: absolute;
      top: 0;
      right: 0;
    }

    .footer {
      // padding: 20px;
      display: flex;
      align-items: end;
      justify-content: end;
    }
  }
}

::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}
</style>
